import { login, refreshToken } from '@/api/login.js'
import { getToken, setToken, removeToken, 
	getUserName, setUserName, removeUserName
} from '@/utils/auth'

const state = {
  token: getToken(),
  name: '',
  avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
}

const mutations = {
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_AVATAR: (state, avatar) => {
		state.avatar = avatar
	}
}

const actions = {
	// user info
	refreshLogin({ commit }) {
		let token = getToken();
		if(!token){
			return;
		}
		return new Promise((resolve, reject) => {
			refreshToken({ AccountToken: token }).then(response => {
				let newToken = response.datas.token;
				commit('SET_TOKEN', newToken)
			})
		});
	},
	// user login 
	login({ commit }, userInfo) {
		console.log('登录方法被触发');
		let username = userInfo.username.trim();
		let password = userInfo.password.trim();
		return new Promise((resolve, reject) => {
			login({ username, password, type: 'Phone' }).then(response => {
				console.log(response);
				let token = response.datas.token;
				commit('SET_TOKEN', token)
				commit('SET_NAME', username)
				setToken(token);
				setUserName(username);
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	// user logout 
	logout({ commit, state, dispatch }) {
		return new Promise((resolve, reject) => {
			commit('SET_TOKEN', '')
			commit('SET_NAME', '')
			
			removeToken();
			removeUserName();
			resolve()
		}).catch(error => {
			reject(error)
		})
	}
}

export default {
	namespaced: true,
	state,
	mutations,
	actions
}
